import request from './request'

enum BlobType {
  ImagePng = 'image/png',
  ImageJpg = 'image/jpeg',
  ImageGif = 'image/gif',
  Webp = 'image/webp',
  XLS = 'application/vnd.ms-excel',
  XLSX = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  CSV = 'text/csv',
  DOC = 'application/msword',
  DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  PDF = 'application/pdf',
  PPT = 'application/vnd.ms-powerpoint',
  PPTX = 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  MP3 = 'audio/mpeg',
  HTML = 'text/html',
  CSS = 'text/css',
  JavaScript = 'text/javascript',
  JSON = 'application/json',
  AVI = 'video/x-msvideo',
  Text = 'text/plain'
}

// 下载blob文件
function downBlob(blob: Blob, type: BlobType, fileName: string) {
  const url = createBlobUrl(blob, type)
  const ele = document.createElement('a')
  ele.setAttribute('download', fileName)
  ele.href = url
  ele.click()
  setTimeout(() => {
    URL.revokeObjectURL(url)
    document.body.removeChild(ele)
  }, 0)
}

// 生成文件的前端url
const createBlobUrl = (source: Blob, type: BlobType) => {
  const blob = new Blob([source], {
    type
  })
  // console.log(blob)
  return URL.createObjectURL(blob)
}

async function fetchBlob(url: string) {
  const blob = await request({
    url,
    method: 'POST',
    responseType: 'blob'
  })
  return blob
}

// 下载文件
async function downloadFile(url: string, fileType: BlobType, fileName: string) {
  const blob: any = await fetchBlob(url)
  downBlob(blob, fileType, fileName)
}

export default {
  downloadFile,
  downBlob,
  createBlobUrl,
  fetchBlob
}
